import { CloseCircleFilled } from '@ant-design/icons';
import { Button } from 'antd';
import { CSSProperties, FC, useEffect, useState } from 'react';
import YmRegisterPersonModal from './YmRegisterPersonModal';

import { useAppSelector } from '@/redux/store';
import { CheckboxItem } from './CheckboxList';
import { gerPersonNum } from './data';
import Ostyle from './index.less';

export type YmRegisterPersonSelectProps = {
  value?: CheckboxItem[];
  style?: CSSProperties;
  onChange?: (value: CheckboxItem[] | undefined) => void;
};

const YmRegisterPersonSelect: FC<YmRegisterPersonSelectProps> = ({ value, style, onChange }) => {
  const { entId } = useAppSelector((state) => state.loginEnt);

  const [selectedPerson, setSelectedPerson] = useState<CheckboxItem[] | undefined>(value);
  const [total, setTotal] = useState<number>(value ? value.length : 0);
  const [isOpen, setOpen] = useState<boolean>(false);

  useEffect(() => {
    // setSelectedPerson(value);
    // const totalCount = value?.reduce((acc, curr) => {
    //   return acc + curr.count;
    // }, 0);
    // setTotal(totalCount ?? 0);

    if (value) {
      gerPersonNum({ entId, publishObject: value as any }).then((res) => {
        setTotal(res ?? 0);
        setSelectedPerson(value);
      });
    }
  }, [value]);

  const onModalOpen = () => {
    setOpen(true);
  };

  const onModalCancel = () => {
    setOpen(false);
  };

  const onClear = () => {
    setTotal(0);
    setSelectedPerson(undefined);

    onChange?.(undefined);
  };

  const onModalOk: any = (e: any, values: CheckboxItem[]) => {
    setSelectedPerson(values);

    // const totalCount = newValues.reduce((acc, curr) => {
    //   return acc + curr.count;
    // }, 0);

    // setTotal(totalCount);

    const newValues = values.map((item) => {
      return {
        id: item.id,
        name: item.name,
        phone: item.phone,
        type: +item.type,
      };
    });

    gerPersonNum({ entId, publishObject: newValues }).then((res) => {
      setTotal(res ?? 0);
      setOpen(false);
      onChange?.(values);
    });
  };

  return (
    <>
      <div className={Ostyle.selpBox}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button type="dashed" onClick={onModalOpen}>
            添加
          </Button>
          <div style={{ marginLeft: 10 }}>
            {total ? (
              <span className={Ostyle.count}>{'共' + total + '人'}</span>
            ) : (
              <span className={Ostyle.placeh}>请添加人员</span>
            )}
          </div>
        </div>

        {Boolean(total) && <CloseCircleFilled style={{ fontSize: '12px', color: '#ccc' }} onClick={onClear} />}
      </div>

      {isOpen && (
        <YmRegisterPersonModal
          value={selectedPerson}
          modalPorps={{ open: isOpen, onCancel: onModalCancel, onClose: onModalCancel, onOk: onModalOk }}
        />
      )}
    </>
  );
};

export default YmRegisterPersonSelect;
